/**
 * 合同处理中心
 */
import React, {Component} from 'react';
import ReactDOM from 'react-dom';

import "./index.less";
import {
    getBusinessInfo,
    high,
    createPage,
    ajax,
    base,
    getUrlParam,
    promptBox,
    cardCache,
    cacheTools,
    toast,
    output,
    print
} from 'nc-lightapp-front';
import {snCreateUIDom, Maybe, getAppPageConfig} from 'src/hrpub/common/utils/utils';
import Header from "../components/Header";
import LeftTree from "../components/LeftTree";
import RightTable from "../components/RightTable";
import SearchTop from "../components/SearchTop";
import TransactionModal from "../components/transaction";
import tableRowAddLink from "../../../public/functions/tableRowAddLink";
import EmptyData from "src/hrpub/common/components/emptyImg";
import NextOperation from "../components/NextOperation";
import OpinionAsk from "../../../public/components/opinionAsk";
import DetailPage from "../components/detailPage";
import NCUploader from 'uap/common/components/NCUploader';
import WpsModal from 'src/hrpub/common/components/wpsPreModel';
import {nodeRefs} from './common';
// const {NCUploader} = high;

const searchId = 'psnquery';

// templateArr/业务处理 传formid
const transactionFormId = {
    sign: 'sign_dataCard',
    change: 'change_dataBase',
    extend: 'extend_dataBase',
    release: 'release_card',
    finish: 'finish_card',
    contopinion: 'contopinionadd',
};

// 加载业务处理模板用
const templateArr = [
    {//续签意见征询
        config: {
            pagecode: '60110313p',
            appcode: '60110313'
        },
        templateId: 'contopinionadd',
        newId: transactionFormId.contopinion,
    }
];

const searchTop = {
    onemonthend: false, //查询从今日起两个月内劳动合同即将到期的人员，默认值为false
    querylast: false, //仅查最新纪录

    termOperator: '1', //合同期限操作符，默认值为1;介于:1,等于:2,大于:3,大于等于:4,小于:5,小于等于:6
    termFromStr: '',// 开始期限，值介于【0,9999】
    contTermStr: '',// 	合同期限，值介于【0,9999】
    termToStr: '',// 结束期限，值介于【0,9999】
    termUint: '2',// 期限单位，默认值为2;年:1,月:2,天:3

    propOperator: '1', //试用期限操作符，默认值为1;介于:1,等于:2,大于:3,大于等于:4,小于:5,小于等于:6
    propFromStr: '', //试用开始期限，值介于【0,9999】
    contPropStr: '', //试用期限，值介于【0,9999】
    propToStr: '', //试用结束期限，值介于【0,9999】
    propUint: '2', //试用期限单位，默认值为2;年:1,月:2,天:3
};
import {getLangCode} from "../../../public/functions/unit";
import {THEME} from "../../../public/theme/theme";

let appConfig = getAppPageConfig() || {};

if (new RegExp(/(localhost|127\.0\.0\.1):3006/g).test(window.location.href)) {
    appConfig.pagecode = '60110301p';
    appConfig.appcode = '60110301'
}

// @handleHash('201908191355', `/ifr?page=201908191355&c=${appConfig.appcode}&p=${appConfig.pagecode}`)
class ContractCenter extends Component {
    constructor(props) {
        super(props);
        if (props.use) {
            props.use.form('make', 'extend', 'change', 'release', 'finish', 'dataCard_add', 'dataBase_add', 'secrerycontCard_add', 'postcontCard_add', 'traincontCard_add')
            props.use.table('contopinionadd')
            props.use.editTable('psninfo', 'ctrtinfo', 'postcontList', 'secrerycontList', 'traincontList', 'psnList')
            props.use.search('psnquery')
        }

        this.props = props;
        this.state = {
            json: {},

            showDetail: false,      //是否显示详情页  false：隐藏； true显示
            conttype: null,      //是否显示详情页  false：隐藏； true显示

            hrorgval: null,                   // 查询左树的数据 主组织
            hrorgobj: {},                   // 查询左树的数据 主组织
            pk_conmodel: '',                   // 浏览接口用
            inposFlag: true,                 // 在职人员标志

            //组件显示参数
            nextOperationVisible: false,     // 下一步操作是否显示

            //业务处理组件
            transactionVisible: false,         // 合同签订是否显示
            transactionFormId: '',             // formid
            transactionModelId: '',            // 业务处理id

            //下一步操作弹窗
            ctrtVOs: '',//下一步操作弹窗需要
            vPks: '',//下一步操作弹窗需要
            warnInf: '',//下一步操作弹窗需要
            pageUrl: '',//下一步操作弹窗需要
            extendtype: '',//下一步操作弹窗需要

            // 查询模板参数
            psnjobs: '',
            searchModalValue: {
                ...searchTop
            },
            currentSelectDepartment: '',
            humanResourceOrganizationValue: {},
            include_child_depts: false,
            include_child_orgs: false,

            // 查询条件
            ...searchTop,

            // 附件管理
            groupLists: [],                         // 上传list
            pk_psndoc_sub: null,                    //合同主键 合同文本查看用

            //ajax参数
            orgPk: '', //左树分支上的pk_org值
            deptPk: '', //左树分支上的pk_dept值
            isOtherNode: false, //是否是左树分支上的其他分支

            // 查询组件id
            queryOid: ''
        }
    }

    /**
     * 刷新
     */
    refresh = (callback) => {
        if (this.state.showDetail) {
            // 刷新详情页
            this.showDetailPage(callback)
        } else {
            // 刷新右表
            this.getRightTable(callback);
        }
    };

    /**
     * 清空右边
     */
    emptyRightTable = () => {
        // 清空右表
        this.rightTableNode.emptyRightTable()
    };

    /**
     * 获取右表
     */
    getRightTable = (callback) => {
        // 查询
        this.rightTableNode.getPsnTable(callback);
    };

    /**
     * 获取左树
     */
    getLeftTreeData = () => {
        // 请求左树
        this.leftTreeNode.getTreeData();
    };

    /**
     * 更新state对象
     * @param data
     * @param callback
     */
    updateState = (data, callback = () => {
    }) => {
        this.setState(data, callback);
    };

    initUIDom() {

        let reqData = [
            {
                rqUrl: '/platform/templet/querypage.do',
                rqJson: `{\n \"pagecode\": \"${this.config.pagecode}\",\n \"appcode\": \"${this.config.appcode}\"\n}`,
                rqCode: 'template'
            },
            {
                rqUrl: '/platform/appregister/queryallbtns.do',
                rqJson: `{\n \"pagecode\": \"${this.config.pagecode}\",\n \"appcode\": \"${this.config.appcode}\"\n}`,
                rqCode: 'button'
            },
            {
                rqUrl: '/platform/appregister/queryappcontext.do',
                rqJson: `{\n \"pagecode\": \"${this.config.pagecode}\",\n \"appcode\": \"${this.config.appcode}\"\n}`,
                rqCode: 'context'
            }
        ];
        snCreateUIDom(this.config, reqData, (data) => {
            // 设置状态
            this.setState({
                buttons: data.button || [],
                context: data.context || {},
                queryOid: data.template[searchId].oid,
            });

            this.setfix(data.template);
            // 先修改 template（this.setfix） 在执行this.tableAddOpr()
            this.tableAddOpr(data.template['ctrtinfo']);
            this.props.meta.setMeta(data && data.template ? data.template : {}, () => {
                // 获取业务处理模板
                templateArr.map(item => {
                    this.getTeplate(item.config, item.templateId, item.newId)
                })
            });
            this.props.button.setButtons(data && data.button ? data.button : []);
        })
    }

    /**
     * 表格添加操作列
     */
    tableAddOpr = (tabledata) => {
        let _this = this;
        // 列表页 的组织名称 添加超链接
        tableRowAddLink(tabledata, 'contractnum', this.onRowClick, 'value');
        let lang = getLangCode();
        let eventWidth = 120;
        let oprWidth = lang === 'english' ? 90 : 80;
        //添加表格操作列
        let event = {
            label: this.state.json["cm6011-000064"],
            attrcode: 'opr',
            itemtype: 'customer',
            //className: "table-opr",
            fixed: 'right',
            width: eventWidth + 'px',
            visible: true,
            render(text, record, index) {
                let recordVal = record.values;
                return (
                    <div className="currency-opr-col">
                        {_this.props.button.createOprationButton(
                            ['contract_body'],
                            {
                                area: 'body',
                                onButtonClick: (props, id, e) => {
                                    _this.headerNode.onBtnOperation(props, id, 'body', record)
                                },
                                popContainer: document.querySelector('.header2')
                            }
                        )}
                    </div>
                );
            }
        };
        // 附件管理
        let fileCol = {
            attrcode: 'file',
            itemtype: 'customer',
            hyperlinkflag: false,
            label: this.state.json['cm6011-000146'], /* 国际化处理： 附件管理*/
            width: oprWidth + 'px',
            textAlign: 'center',
            visible: true,
            fixed: 'right',
            render(text, record, index) {
                let billId = record.values.pk_psndoc_sub.value;
                return (
                    <a style={{cursor: 'pointer'}}>
                        <i className="icon iconfont icon-fujianshenpi" onClick={(eve) => {
                            _this.setState({
                                showUploader: true,
                                pk_psndoc_sub: billId
                            })
                        }}/>
                    </a>
                )
            }
        };
        tabledata.items.push(fileCol);
        tabledata.items.push(event);
    };

    setfix = (template) => {
        let tableobj = {
            psninfo: ['pk_psndoc.code', 'pk_psndoc.name', 'pk_post', 'pk_dept'],
            ctrtinfo: ['contractnum', 'pk_majorcorp', 'pk_psndoc.code', 'pk_psndoc.name'],
        };
        for (let key in tableobj) {
            if (!template.hasOwnProperty(key)) return;
            if (!template[key].hasOwnProperty('items')) return;
            let items = template[key].items;
            let tableKey = tableobj[key];
            items.forEach(item => {
                if (tableKey.includes(item.attrcode)) {
                    let attrcode = item.attrcode;
                    item.fixed = 'left';
                    item.itemtype = 'customer';
                    let style = {
                        "overflow": "hidden",
                        "text-overflow": "ellipsis",
                        "white-space": "nowrap",
                    };
                    let width = item.width || '120px';
                    let endIndex = width.indexOf('px');
                    if (endIndex !== -1) {
                        let widthNum = width.substring(0, endIndex);
                        width = widthNum - 15 + 'px';
                    }
                    style.width = width;
                    item.render = (text, record, index) => {
                        return (
                            <div className="currency-opr-col" style={style}>
                                {record.values && record.values[attrcode] && record.values[attrcode]['display'] || record.values[attrcode]['value']}
                            </div>
                        );
                    }
                }
            })
        }
    };

    onRowClick = (record, index) => {
        this.rightTableNode.clickContractNum(record, index)
    };

    /**
     * 获取 业务处理模板
     * @param config   ·{pagecode: '',appcode: ''}
     * @param templateId    模板id
     * @param newId         模板id
     */
    getTeplate(config, templateId, newId) {
        this.props.createUIDom(config, (data) => {
            let meta = this.props.meta.getMeta() || {};
            if (typeof templateId === 'string' && data.template.hasOwnProperty(templateId)) {
                meta[newId] = data.template[templateId];
            } else if (Array.isArray(templateId)) {
                templateId.map((key, index) => {
                    if (data.template.hasOwnProperty(templateId[index])) {
                        meta[(newId[index])] = data.template[key];
                    }
                })
            }
            if (meta['contopinionadd']) {
                meta['contopinionadd'].items.forEach(item => {
                    if (item.attrcode === 'psncode' || item.attrcode === 'pk_psndoc') {
                        item.fixed = 'left';
                    }
                });
            }
            this.props.meta.setMeta(meta);
        });
    }

    /**
     * 页面初始化
     */
    pageInit() {
        this.initUIDom();
    }

    // 附件的关闭点击
    onHideUploader = () => {
        this.setState({
            showUploader: false,
            groupLists: []
        })
    };

    //获取当前附件列表
    getGroupList = (list) => {
        //要在state里面顶一个变量，用来存储列表数组
        this.setState({
            groupLists: list
        })
    };


    /**
     * 搜索dom点击查找
     */
    goSearch() {
        let {
            onemonthend,
            querylast,
            termOperator,
            termFromStr,
            contTermStr,
            termToStr,
            termUint,
            propOperator,
            propFromStr,
            contPropStr,
            propToStr,
            propUint
        } = this.state;

        let searchObj = {
            onemonthend,
            querylast,
            termOperator,
            termFromStr,
            contTermStr,
            termToStr,
            termUint,
            propOperator,
            propFromStr,
            contPropStr,
            propToStr,
            propUint,
            ...this.props.search.getQueryInfo(searchId, true)
        };
        this.updateState({
            searchModalValue: searchObj
        }, () => {
            // 查询右表
            this.rightTableNode.reloadTable((res) => {
                let num = Maybe.of(res).getValue(['data', 'psninfo', 'pageInfo', 'total']) || 0;
                toast({
                    color: 'success',
                    content: this.state.json['cm6011-000107'] + num + this.state.json['cm6011-000108']
                });//刷新成功！
            });
            // 关闭查询区
            this.props.search.openAdvSearch(searchId, false);
        });
    }

    componentWillMount() {
        let callback = (json, status, inlt) => {
            if (status) {
                this.setState({json, inlt}, () => {
                }) // 保存json和inlt到页面state中并刷新页面
            }
        };
        this.props.MultiInit.getMultiLang({moduleId: 'cm6011', domainName: 'hrcm', callback})

    }

    componentDidMount() {
        // window.location.hash = '#/ifr?page=201908191355';
        this.config = getAppPageConfig();
        if (!('remove' in Element.prototype)) {
            Element.prototype.remove = function () {
                if (this.parentNode) {
                    this.parentNode.removeChild(this);
                }
            };
        }
        this.pageInit();
    }

    /**
     * 打开意见征询弹窗
     */
    openOpinionAskNode = (psnjobs) => {
        // let data = this.props.editTable.getCheckedRows('psninfo');
        // let rows = [];
        // data.map(item => {
        //     rows.push(item.data)
        // });
        this.opinionAskNode.open(psnjobs);

    };

    /**
     * 显示详情页
     */
    showDetailPage = (callback) => {
        this.updateState({
            showDetail: true
        }, () => {
            this.detailPageNode.getDetailData(callback);
        });
    };

    /**
     * 显示业务处理弹窗
     */
    showTransaction = (extendtype) => {
        this.updateState({
            transactionVisible: true
        }, () => {
            this.transactionNode.initPage(extendtype)
        });
    };

    render() {
        let {search, DragWidthCom} = this.props;
        const {
            json,
            showUploader,
            hrorgval,
            inposFlag,
            searchModalValue,
            orgPk,
            deptPk,
            isOtherNode,
            showDetail,
            pk_psndoc_sub,
            onemonthend,
            querylast,
            termOperator,
            termFromStr,
            contTermStr,
            termToStr,
            termUint,
            propOperator,
            propFromStr,
            contPropStr,
            propToStr,
            hrorgobj,
            propUint
        } = this.state;
        const componentProps = {
            ...this.props,
            json,
            hrorgval,
            inposFlag,
            searchModalValue,
            orgPk,
            deptPk,
            isOtherNode,
            showDetail,
            pk_psndoc_sub,
            onemonthend,
            querylast,
            termOperator,
            termFromStr,
            contTermStr,
            termToStr,
            termUint,
            propOperator,
            propFromStr,
            contPropStr,
            propToStr,
            propUint,
            hrorgobj,
            updateState: this.updateState,
            emptyRightTable: this.emptyRightTable,
            refresh: this.refresh,
            showTransaction: this.showTransaction,
        };
        return (
            <div className={`contract-center ${THEME.bgCommon}`}>
                <OpinionAsk
                    {...this.props}
                    orgVal={{refpk: this.state.hrorgval}}
                    // confirmAction={this.getMainTableData}
                    // confirmAskAction={this.getMainTableData}
                    ref={node => this.opinionAskNode = node}
                />
                {this.config && <NextOperation
                    {...componentProps}
                    ctrtVOs={this.state.ctrtVOs}
                    vPks={this.state.vPks}
                    warnInf={this.state.warnInf}
                    pageUrl={this.state.pageUrl}
                    psnjobs={this.state.psnjobs}
                    querylast={this.state.querylast}
                    transactionModelId={this.state.transactionModelId}
                    extendtype={this.state.extendtype}
                    config={this.config}
                    nextOperationVisible={this.state.nextOperationVisible}
                />}
                {this.config && <TransactionModal
                    {...componentProps}
                    transactionVisible={this.state.transactionVisible}
                    extendtype={this.state.extendtype}
                    formId={this.state.transactionFormId}
                    config={this.config}
                    transactionModelId={this.state.transactionModelId}
                    ref={node => this.transactionNode = node}
                />}
                {/* search */}
                <div style={{display: 'none'}}>
                    {search.NCCreateSearch(searchId, {
                        id: searchId,
                        clickSearchBtn: this.goSearch.bind(this),
                        onlyShowAdvArea: false,
                        showAdvSearchPlanBtn: true,
                        saveSearchPlan: true,
                        onlyShowSuperBtn: true,
                        advSearchClearEve: () => {
                            this.updateState({
                                onemonthend: false, //查询从今日起两个月内劳动合同即将到期的人员，默认值为false
                                querylast: false, //仅查最新纪录

                                termOperator: '1', //合同期限操作符，默认值为1;介于:1,等于:2,大于:3,大于等于:4,小于:5,小于等于:6
                                termFromStr: '',// 开始期限，值介于【0,9999】
                                contTermStr: '',// 	合同期限，值介于【0,9999】
                                termToStr: '',// 结束期限，值介于【0,9999】
                                termUint: '2',// 期限单位，默认值为2;年:1,月:2,天:3

                                propOperator: '1', //试用期限操作符，默认值为1;介于:1,等于:2,大于:3,大于等于:4,小于:5,小于等于:6
                                propFromStr: '', //试用开始期限，值介于【0,9999】
                                contPropStr: '', //试用期限，值介于【0,9999】
                                propToStr: '', //试用结束期限，值介于【0,9999】
                                propUint: '2', //试用期限单位，默认值为2;年:1,月:2,天:3
                            })
                        },
                        addAdvBody: () => {
                            return <SearchTop
                                {...componentProps}
                            />
                        },
                        replaceSuperBtn: this.state.json['jf6005-000063']/* 国际化处理： 查询*/
                    })}
                </div>
                {/* file */}
                <div className="nc-faith-demo-div2">
                    {/* 这里是附件上传组件的使用，需要传入三个参数 */}
                    {showUploader && <NCUploader
                        disableDownload={false}
                        billId={this.state.pk_psndoc_sub}
                        // billNo={''}
                        // target={target}
                        customize={{uploadTrpe: '0'}}
                        placement={'bottom'}
                        getGroupList={this.getGroupList}
                        uploadTitle={this.state.json['jf6005-000062']}/* 国际化处理： 附件管理*/
                        onHide={this.onHideUploader} // 关闭功能
                    />
                    }
                </div>

                {/* header */}
                <Header
                    {...componentProps}
                    transactionFormId={transactionFormId}
                    queryOid={this.state.queryOid}
                    getLeftTreeData={this.getLeftTreeData}
                    openOpinionAskNode={this.openOpinionAskNode}
                    conttype={this.state.conttype}
                    ref={node => {
                        this.headerNode = node;
                    }}
                />
                <div className={'contract-center-list'} style={{display: showDetail ? 'none' : ''}}>
                    {/*树表*/}
                    {hrorgval ? <DragWidthCom
                        // 左树区域
                        leftDom={
                            <LeftTree
                                {...componentProps}
                                ref={node => {
                                    this.leftTreeNode = node;
                                }}
                            />
                        }
                        // 右卡片区域
                        rightDom={
                            <RightTable
                                {...componentProps}
                                showDetailPage={this.showDetailPage}
                                ref={node => {
                                    this.rightTableNode = node;
                                }}
                            />
                        }     //右侧区域dom
                        defLeftWid='250px'      // 默认左侧区域宽度，px/百分百
                    /> : <EmptyData text={this.state.json['cm6011-000096']}/>}
                </div>
                {this.config && showDetail && <DetailPage
                    {...componentProps}
                    conttype={this.state.conttype}
                    pagecode={this.config.pagecode}
                    appcode={this.config.appcode}
                    ref={node => {
                        this.detailPageNode = node
                    }}
                />}
                 <WpsModal
                    {...componentProps}
                    onRef ={ref => nodeRefs.wpsview = ref}
                    appcode={getAppPageConfig().appcode}
                    pk_org={this.state.hrorgval}
                   
                />
            </div>
        )
    }
}

let billinfo = [
    {
        billtype: 'grid',
        pagecode: appConfig.pagecode,
        bodycode: 'psninfo'
    },
    {
        billtype: 'grid',
        pagecode: appConfig.pagecode,
        bodycode: 'ctrtinfo'
    },
    {
        billtype: 'form',
        pagecode: appConfig.pagecode,
        headcode: 'make'

    },
    {
        billtype: 'form',
        pagecode: appConfig.pagecode,
        headcode: 'extend'

    },
    {
        billtype: 'form',
        pagecode: appConfig.pagecode,
        headcode: 'change'

    },
    {
        billtype: 'form',
        pagecode: appConfig.pagecode,
        headcode: 'release'

    },
    {
        billtype: 'form',
        pagecode: appConfig.pagecode,
        headcode: 'finish'

    }
];
let ContractCenterModal = createPage({
    // billinfo
})(ContractCenter);
ReactDOM.render(<ContractCenterModal/>, document.querySelector('#app'));
export default ContractCenter
